package com.aiyige.page.user.behavior;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

import com.aiyige.R;

/**
 * Created by zhuyakun on 2017/10/19.
 */

public class UserPageBackButtonBehavior extends CoordinatorLayout.Behavior<ImageView> {
    int currentImageResId = R.drawable.user_back;
    float nestedScrollDistance;
    View dependency;

    public UserPageBackButtonBehavior() {
    }

    public UserPageBackButtonBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, ImageView child, View dependency) {
        if (dependency.getId() == R.id.appbar) {
            this.dependency = dependency;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onLayoutChild(CoordinatorLayout parent, ImageView child, int layoutDirection) {
        nestedScrollDistance = dependency.getMeasuredHeight() - child.getResources().getDimension(R.dimen.user_page_title_bar_height) - child.getResources().getDimension(R.dimen.user_page_tab_height);
        return super.onLayoutChild(parent, child, layoutDirection);
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, ImageView child, View dependency) {
        float x = Math.abs(dependency.getTranslationY()) / nestedScrollDistance;
        float y = (float) (0.5 * Math.cos(2 * Math.PI * x) + 0.5);
        child.setAlpha((float) Math.pow(y, 3));
        if (x < 0.5f && (currentImageResId != R.drawable.user_back)) {
            child.setImageResource(R.drawable.user_back);
            currentImageResId = R.drawable.user_back;
        }
        if (x > 0.5f && (currentImageResId != R.drawable.sign_in_back)) {
            child.setImageResource(R.drawable.sign_in_back);
            currentImageResId = R.drawable.sign_in_back;
        }
        return false;
    }
}
